#include "widget.h"
#include "ui_widget.h"
#include <QNetworkRequest>
#include <QUrl>
#include <QJsonArray>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QJsonObject>
#include <QJsonParseError>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    manager = new QNetworkAccessManager;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    //获取文本框内容
    QString text = ui->inputEdit->toPlainText();

    ui->inputEdit->clear();

    ui->outputEdit->insertPlainText("-->");
    ui->outputEdit->insertPlainText(text);
    ui->outputEdit->insertPlainText("\n\n");

    QNetworkRequest request;
    request.setUrl(QUrl("https://api.deepseek.com/chat/completions"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Accept", "application/json");
    request.setRawHeader("Authorization", "Bearer sk-d53cf4d66cbb4c3f8410e34b6f6b9ffe");

    QJsonArray messages;

    QJsonObject systemMsg;
    systemMsg["role"] = "system";
    systemMsg["content"] = "You are a helpful assistant";

    QJsonObject userMsg;
    userMsg["role"] = "user";
    userMsg["content"] = text;

    messages.append(systemMsg);
    messages.append(userMsg);

    QJsonObject requestBody;
    requestBody["messages"] = messages;
    requestBody["model"] = "deepseek-chat";
    requestBody["max_tokens"] = 2048;
    requestBody["stream"] = true;
    requestBody["temperature"] = 1;

    //发送请求
    QNetworkReply *reply = manager->post(request, QJsonDocument(requestBody).toJson());

    //处理数据
    connect(reply, &QNetworkReply::readyRead,this, [=]{
        while (reply->canReadLine())
        {
            QString line = reply->readLine().trimmed();

            if (line.startsWith("data:"))    //以 data: 开头的数据
            {
                line.remove(0, 6);

                QJsonParseError error;

                QJsonDocument doc = QJsonDocument::fromJson(line.toUtf8(), &error);

                if (error.error == QJsonParseError::NoError)   //是个json对象
                {
                    QString content = doc.object()["choices"].toArray().first()
                                          .toObject()["delta"].toObject()["content"].toString();

                    if (!content.isEmpty())
                    {
                        ui->outputEdit->moveCursor(QTextCursor::End);
                        ui->outputEdit->insertPlainText(content);
                    }
                }
            }
        }
    });

    connect(reply, &QNetworkReply::finished,this,[=]{
        ui->outputEdit->moveCursor(QTextCursor::End);
        ui->outputEdit->insertPlainText("\n\n\n\n");

        reply->deleteLater();
    });
}

